//
//  ToolVideoEditViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "ToolVideoEditViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LFVideoEditingController.h"
#import "AVAsset+LFMECommon.h"
#import <PhotosUI/PhotosUI.h>

@interface ToolVideoEditViewController ()<LFVideoEditingControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *editBtn;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *infoView;

@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) UIImage *firstImage;
@property (nonatomic, strong) LFVideoEdit *videoEdit;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, weak) AVPlayerLayer *playerLayer;
@end

@implementation ToolVideoEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"视频编辑";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtnImage:[UIImage systemImageNamed:@"plus"]]) addTarget:self action:@selector(addPress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];
    // Do any additional setup after loading the view from its nib.
}

- (void)dealloc {
    [self.player removeObserver:self forKeyPath:@"status"];
    [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    _playerLayer.frame = CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - IS_iPhoneX_Bottom - 44 - 20);
}

- (void)addPress {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//指定数据来源是相册
    picker.mediaTypes = @[@"public.movie"];
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)editPress {
    if (!self.infoView.hidden) {
        [self showHUDAlert:@"未添加视频"];
        return;
    }
    LFVideoEditingController *lfVideoEditVC = [[LFVideoEditingController alloc] init];
    lfVideoEditVC.delegate = self;
    if (self.videoEdit) {
        lfVideoEditVC.videoEdit = self.videoEdit;
    } else {
        [lfVideoEditVC setVideoURL:self.url placeholderImage:self.firstImage];
    }
    [self.navigationController setNavigationBarHidden:YES];
    [self.navigationController pushViewController:lfVideoEditVC animated:NO];
}

- (IBAction)savePress {
    if (!self.infoView.hidden) {
        [self showHUDAlert:@"未添加视频"];
        return;
    }
    PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
    [photoLibrary performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:self.url];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [self showHUDAlert:@"已保存到系统相册"];
            } else {
                [self showHUDAlert:@"保存失败"];
            }
        });
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    self.infoView.hidden = YES;
    self.url = [info objectForKey:UIImagePickerControllerMediaURL];
    //并且赋值给声明好的imageView
    [self.player removeObserver:self forKeyPath:@"status"];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.url options:nil];
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    [self.player replaceCurrentItemWithPlayerItem:item];
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    _playerLayer.player = self.player;
    self.firstImage = [asset lf_firstImage:nil];
    self.videoEdit = nil;
    //最后模态返回 最初的 控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        if (self.player.status == AVPlayerStatusReadyToPlay) {
            [self.player play];
        } else {
            NSLog(@"视频解析失败!");
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - LFVideoEditingControllerDelegate
- (void)lf_VideoEditingControllerDidCancel:(LFVideoEditingController *)videoEditingVC {
    [self.navigationController popViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:NO];
    [self.player seekToTime:kCMTimeZero];
    [self.player play];
}

- (void)lf_VideoEditingController:(LFVideoEditingController *)videoEditingVC didFinishPhotoEdit:(LFVideoEdit *)videoEdit {
    [self.navigationController popViewControllerAnimated:NO];
    [self.navigationController setNavigationBarHidden:NO];
    [self.player removeObserver:self forKeyPath:@"status"];
    if (videoEdit && videoEdit.editFinalURL) {
        self.player = [AVPlayer playerWithURL:videoEdit.editFinalURL];
    } else {
        self.player = [AVPlayer playerWithURL:self.url];
    }
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    _playerLayer.player = self.player;
    self.videoEdit = videoEdit;
}

- (void)initView {
    [self.bottomView setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - 44 - 10, SCREEN_WIDTH_DEVICE, 44)];
    [self.infoView setFrame:CGRectMake(SCREEN_WIDTH_DEVICE - 157, IS_iPhoneX_Top + NavBarHeight, 157, 103)];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:self.url options:nil];
    self.firstImage = [asset lf_firstImage:nil];
    _player = [AVPlayer playerWithURL:self.url];
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    playerLayer.frame = CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Top - NavBarHeight - IS_iPhoneX_Bottom - 44 - 20);
    [self.view.layer addSublayer:playerLayer];
    _playerLayer = playerLayer;
}

@end
